function str_replace(haystack, needle, replacement) {
	var temp = haystack.split(needle);
	return temp.join(replacement);
}

function str_remove_line_break(data)
{
  	temp=data.substring(0,1);
		if ((temp =="\r") || (temp == "\n"))
			data=data.substring(1);
		temp=data.substring(0,1);
		if ((temp =="\r") || (temp == "\n"))
			data=data.substring(1);
		return data;
}
 
var article_no_need_reload=false;

$(document).ready(function() {
	article_reload(1);
	$("#article_cat").change(function() {
		article_reload(1);
	});
	$("#article_items").change(function() {
		var id = $("#article_items").val();
		show_article(id);
	});
});


function article_reload(type)
{
	if (article_no_need_reload) return;
	article_no_need_reload=true; // force that no need to reload when dropdown box change
	hide_button();
	
	if (type == 1) {
		var t2=Math.floor(Math.random()*99999).toString();
		var cat_id = $("#article_cat").val();
		//alert("index.php?module=articlemodule&action=get_article&ajax_action=1&cat_id="+cat_id+"&t2="+t2);
		$.post("index.php?module=articlemodule&action=get_article&ajax_action=1&cat_id="+cat_id+"&t2="+t2,
			function(data){
				//data=data.substring(2); // remove enter char
				data=str_remove_line_break(data);
				//alert(data);
				if ((data.length>=t2.length) && (data.substring(0,t2.length) == t2))			
				{
					data=data.substring(t2.length); // remove t2 security check
					$("#article_items").html(data);
					show_button();
					article_no_need_reload=false;
				}
				else
				{
					article_no_need_reload=false;
					return;
				}
			});
	} // end of reload items
	article_no_need_reload=false;
	show_button();
}

function show_button()
{
	$("#article_span_loading").fadeOut();
}

function hide_button()
{
	$("#article_span_loading").fadeIn();
}


function show_article(id)
{
	if ((id == -1) || (id == "-1")) return;
	if (article_no_need_reload) return;
	article_no_need_reload=true; // force that no need to reload when dropdown box change
	hide_button();
	var t2=Math.floor(Math.random()*99999).toString();
		//alert("index.php?module=articlemodule&action=view_acticle&ajax_action=1&id="+id+"&t2="+t2);
		$.post("index.php?module=articlemodule&action=view_article&ajax_action=1&id="+id+"&t2="+t2,
			function(data){
				//data=data.substring(2); // remove enter char
				data=str_remove_line_break(data);
				if ((data.length>=t2.length) && (data.substring(0,t2.length) == t2))			
				{
					data=data.substring(t2.length); // remove t2 security check
					$("#article_result").html(data);
					show_button();
					article_no_need_reload=false;
				}
				else
				{
					article_no_need_reload=false;
					return;
				}
			});
	article_no_need_reload=false;
	show_button();
}
